
import { Button, Row, Col, Icon, message, Modal } from 'antd';
import { WeaTab, WeaAlertPage, WeaProgress, WeaSearchGroup, WeaFormItem, WeaLocaleProvider, WeaTools } from 'ecCom';
import { inject, observer } from "mobx-react";
import { toJS } from 'mobx';
import { WeaTableNew, WeaSwitch } from 'comsMobx';
import { Condition } from "../../list/listCondition"
import TaskInfoDialog from '../../dialog/taskDialog'
import ExchangeDialog from '../../dialog/exchangeDialog'
import ShareDialog from '../../dialog/shareDialog'
import RelateListDialog from "../../dialog/relateListDialog"
import EditPrjTaskDataDialog from "../../dialog/editPrjTaskDataDialog"
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
@observer
class TaskList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            taskid: "",
            coWorkVisiable: false,
            workPlanVisible: false
        }
    }

    componentDidMount() {
        const { contentStore, prjid } = this.props;
        contentStore.initData(prjid);

        if(!window.weaWorkplan && !window.weaCowork){
            eventRegister.loadModule('f_workplan', ()=> {
                eventRegister.loadModule('f_cowork', ()=> {
                }, ()=> {
                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                    alert("加载协作模块失败，请联系系统管理员！");
                });
            }, ()=> {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载日程模块失败，请联系系统管理员！");
            });
            return;
        }
        if(window.weaWorkplan && !window.weaCowork){
            eventRegister.loadModule('f_cowork', ()=> {
            }, ()=> {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载协作模块失败，请联系系统管理员！");
            });
        }else{
            eventRegister.loadModule('f_workplan', ()=> {
            }, ()=> {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载协作模块失败，请联系系统管理员！");
            });
        }
      
    }

    render() {
        const account = WeaTools.ls.getJSONObj('theme-account');
        const { contentStore } = this.props;
        const { taskListTableStore, taskListRight: { hasRight, verified }, taskListTabs, taskListform, showSearchAd, taskListSearchParams, shareStore, exchangeStore, taskInfoStore, reLoad, prjid, showEditTask } = contentStore;
        const formParams = taskListform.getFormParams() || {};
        const rowSelection = {
            onChange(selectedRowKeys, selectedRows) {
                taskInfoStore.onRowSelect(selectedRowKeys);
            }
        };
        if (verified && !hasRight) {
            return (<WeaAlertPage >
                <div style={{ color: '#000' }}>
                    {getLabel(2012, "对不起，您暂时没有权限！")}
                </div>
            </WeaAlertPage>
            )
        }
        if (verified && hasRight) {
            return (
                <div >
                    {
                        <WeaTab
                            datas={toJS(taskListTabs)}
                            keyParam="key"  //主键
                            selectedKey={taskListSearchParams.version}
                            buttonsAd={this.getAdButtons()}
                            searchType={['base', 'advanced']}
                            searchsBaseValue={formParams.taskname}
                            setShowSearchAd={bool => { contentStore.setShowSearchAd(bool) }}
                            hideSearchAd={() => contentStore.setShowSearchAd(false)}
                            searchsAd={
                                <div><Condition listStore={contentStore} form={taskListform} onEnterSearch={this.onEnterSearch} ></Condition></div>
                            }
                            showSearchAd={showSearchAd}
                            onSearch={v => { contentStore.getPrjTaskList() }}
                            onSearchChange={v => { contentStore.setFormFields({ taskname: { value: v } }) }}
                            onChange={this.changeVision}
                        />
                    }
                    <div>
                        {this.getQuickSearch()}
                    </div>
                    <WeaTable
                        comsWeaTableStore={taskListTableStore}
                        childrenColumnName="subListspan"
                        hasOrder={true}
                        needScroll={false}
                        register_table={() => reLoad(taskListTableStore)}
                        getColumns={c => this.reRenderColumns(c)}
                        onOperatesClick={this.onOperatesClick.bind(this)}
                        rowSelection={rowSelection}
                    />
                    <ShareDialog contentStore={contentStore} />
                    <ExchangeDialog contentStore={exchangeStore} />
                    <TaskInfoDialog contentStore={taskInfoStore} prjid={prjid} callBack={() => { contentStore.initData(prjid); }} />
                    <RelateListDialog contentStore={contentStore} />
                    <EditPrjTaskDataDialog ref="editPrjTaskData" contentStore={contentStore} visible={showEditTask} />
                    {window.weaCowork && window.weaCowork.com && window.weaCowork.com.CreateCowork && this.state.coWorkVisiable && this.state.taskid !== "" && (
                        <window.weaCowork.com.CreateCowork
                            initAddQuery={
                                {
                                    relatedType: "task",
                                    ids: this.state.taskid
                                }
                            }
                            onCancel={() => {
                                this.setState({
                                    coWorkVisiable: false
                                });
                            }}
                        />)
                    }

                    {
                        window.weaWorkplan && window.weaWorkplan.com && window.weaWorkplan.com.WorkPlanCreate &&
                        (<window.weaWorkplan.com.WorkPlanCreate
                            type={"create"}//新建为'create',查看为'preview',编辑edit,共享share
                            visible={this.state.workPlanVisible}//显隐受控
                            doClose={() => { this.setWorkPlanVisible(false); }}//关闭回调
                            onlyClose={() => { this.setWorkPlanVisible(false) }}//关闭回调,只做关闭操作
                            workPlanId={""} //日程id，1查看日程时用到
                            createConditionParams={[]}//创建的默认值日期和时间,没有传[]
                            activeKey={""} //查看页面显示的面板1是基本信息，7是相关交流
                            //changeTab={(key) => { }}//查看页面切换面板的回调
                            selectUser={account && account.userid}//新建日程的创建人id
                            workPlanTypeOptions={"2"}//客户模块的新建日程，普通新建传'',客户新建传3
                            crmIDs={[]}//通过客户模块新建日程，并自动带出相关客户,[{'id':'','name':''}]
                            projectid={prjid}
                            taskid={this.state.taskid}
                            description={""}//客户模块需求，支持新建时传入的'基本信息-内容'
                        />)
                    }
                </div>)
        }
        return <div></div>
    }
    reRenderColumns(columns) {
        columns.forEach(c => {
            if (c.dataIndex == 'finish') {
                c.render = function (text, record) {
                    return <span className='wea-prj-progressStyle' >
                        <WeaProgress percent={record.finish || 0} strokeColor={record.finishspan} />
                    </span>
                }
            } else {
                c.render = function (text, record) {
                    let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                    return <span dangerouslySetInnerHTML={{ __html: valueSpan }}></span>
                }
            }
        })
        return columns;
    }
    getQuickSearch() {
        const { taskListQuickitems, taskListquickform, getPrjTaskList } = this.props.contentStore;
        const { isFormInit } = taskListquickform;
        let group = [];
        const formParams = taskListquickform.getFormParams();
        isFormInit && toJS(taskListQuickitems).map(c => {
            let items = [];
            c.items.map((fields, index) => {
                items.push({
                    com: (<WeaFormItem
                        label={`${fields.label}`}
                        labelCol={{ span: `${fields.labelcol}` }}
                        wrapperCol={{ span: `${fields.fieldcol}` }}>
                        <WeaSwitch fieldConfig={fields} form={taskListquickform} onChange={(res) => { getPrjTaskList({ [fields.domkey[0]]: res[fields.domkey[0]].value }); }} />
                    </WeaFormItem>),
                    colSpan: 1,
                })
            });
            group.push(<WeaSearchGroup needTigger={true} col={4} title={getLabel(32840, "基本条件")} showGroup={true} items={items} />)
        });
        return group;
    }

    onOperatesClick(record, index, operate, flag) {
        let that = this;
        const { contentStore } = this.props;
        const { shareStore, exchangeStore, taskInfoStore, prjid } = contentStore;
        let _href = operate && operate.href ? operate.href : "";
        let fn = _href.replace("javascript:", "");
        fn = fn.substring(0, fn.indexOf('('));

        if (fn != "") {
            if ("onShare" == fn) {  //共享
                shareStore.handleShareDialog(true, "task", record.randomFieldId, {})
            } else if ('onNewCowork' == fn) {   //新建协作
                this.setState({ taskid: record.randomFieldId, coWorkVisiable: true });
                const coworkStoreMap = window.weaCowork.store && window.weaCowork.store.coworkStoreMap;
                const cowortore = coworkStoreMap && coworkStoreMap.getMapStore(3);
                cowortore && cowortore.setCreateState({ showNewCowork: true, createOrEdit: 0 });
            } else if ('onNewWorkplan' == fn) {   //新建日程
                this.setState({ taskid: record.randomFieldId, workPlanVisible: true });
            } else if ('onAddSubTask' == fn) {   //新建子任务
                taskInfoStore.handleDialog(true, "add", '', { prjid: prjid, parentid: record.randomFieldId });
            } else if ('onEditTask' == fn) {   //编辑
                taskInfoStore.handleDialog(true, "edit", record.randomFieldId);
            } else if ('onDiscuss' == fn) {   //相关交流
                exchangeStore.handleExchangeDialog(true, "task", record.randomFieldId, {})
            } else if ('onDel' == fn) {   //删除
                taskInfoStore.delTask("del", record.randomFieldId);
            }
        }
    }

    changeVision = (key) => {
        const { contentStore } = this.props;
        contentStore.getPrjTaskList({ version: key == "0" ? "" : key })
    }

    getAdButtons = () => {
        const { contentStore } = this.props;
        const { getPrjTaskList, setShowSearchAd, clearFormFields } = contentStore;
        return [
            (<Button type="primary" onClick={() => { getPrjTaskList(); setShowSearchAd(false); }}>{getLabel(197, "搜索")}</Button>),
            (<Button type="ghost" onClick={() => { clearFormFields(); }}>{getLabel(2022, "重置")}</Button>),
            (<Button type="ghost" onClick={() => { setShowSearchAd(false) }}>{getLabel(201, "取消")}</Button>)
        ];
    }

    setWorkPlanVisible = (bool) => {
        this.setState({ workPlanVisible: bool })
    }

    onEnterSearch=() =>{
        const { contentStore } = this.props;
        contentStore.getPrjTaskList();
        contentStore.setShowSearchAd(false);
    }

}

export default TaskList;
